import React, {useState, useEffect} from 'react'
import {Button, Form, message} from 'antd'
import {connect, history} from 'umi'
import styles from './index.less'
import PersonalInformation from '../components/PersonalInformation'
import ImageInfo from '../components/ImageInfo'
import CreditInformation from '../components/CreditInformation'
import HealthInformation from '../components/HealthInformation'
import BankCard from '../components/BankCard'
import EmergencyContact from '../components/EmergencyContact'
import {getDict} from '@/service/common/dict'
import {
	addDriverRequest,
	driverDetailRequest,
	driverEditRequest,
	createDriverCode,
} from '@/service/customer/driver'
import {getCompany} from '@/service/common/index'
import {translateDataToTree} from '@/utils/common/index'
import Modal from '@/components/Modal'

const PageType = {
	add: 'add',
	edit: 'edit',
}

const add = (props: any) => {
	const routerQuery = props.location.query
	const pageType = routerQuery.type
	const [companyData, setCompanyData] = useState<any[]>([])
	const [personalInformationFrom]: any = Form.useForm()
	const [creditInformationFrom]: any = Form.useForm()
	const [healthInformationForm]: any = Form.useForm()
	const [emergencyContactFrom]: any = Form.useForm()
	const [bankCardForm]: any = Form.useForm()
	const [fileList, setFileList] = useState<any>([])
	const [physicalFileList, setPhysicalFileList] = useState<any>([])
	const [detailRecord, setDetailRecord] = useState<any>({})
	// const [driverId, setDriverId] = useState('')
	const [dict, setDict] = useState<any>({
		yes_no: [],
		education: [],
		driver_channel_source: [],
		driver_status: [],
		online_car_hailing_experience: [],
		work_experience: [],
		relationship: [],
		sex: [],
	})
	const [formData, setFormData] = useState<any>({}) // 暂存的表单数据
	const [isModalOpen, setIsModalOpen] = useState(false) // 二次确认弹窗
	const [btnLoading, setBtnLoading] = useState(false) // 按钮loading

	/** 获取所属公司数据 */
	const onCompany = () => {
		// eslint-disable-next-line react/destructuring-assignment
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setCompanyData(list as any)
			}
		})
	}
	// 生成司机id
	const createDriverCodeData = async () => {
		const data = await createDriverCode()
		if (data.code === 0) {
			// setDriverId(data.data)
			personalInformationFrom.setFieldsValue({
				driverId: data.data,
			})
		}
	}

	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'yes_no',
					'education',
					'driver_channel_source',
					'driver_status',
					'online_car_hailing_experience',
					'work_experience',
					'relationship',
					'sex',
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
		onCompany()
		if (pageType === PageType.add) {
			createDriverCodeData()
		}
	}, [])

	// 获取司机详情
	const getDriverDetail = async () => {
		const data = await driverDetailRequest({
			driverId: routerQuery.id,
			status: routerQuery.status,
			orgId: routerQuery.orgId,
		})
		if (data.code === 0) {
			setDetailRecord(data.data)
		}
	}

	useEffect(() => {
		if (pageType === PageType.edit) {
			getDriverDetail()
		}
	}, [pageType, routerQuery.id])

	// 新增保存和编辑保存
	const onSave = async () => {
		const personForm = await personalInformationFrom.validateFields()
		const creditFrom = await creditInformationFrom.validateFields()
		const healthInform = await healthInformationForm.validateFields()
		const bankForm = await bankCardForm.validateFields()
		const emergencyContact = await emergencyContactFrom.validateFields()
		const obj = {
			...personForm,
			...creditFrom,
			...healthInform,
			...bankForm,
			...emergencyContact,
		}
		if (personForm && bankForm && emergencyContact) {
			setFormData(obj)
			setIsModalOpen(true)
		}
	}

	const onSubmit = () => {
		setBtnLoading(true)
		let request: any
		const obj = {...formData}
		obj.cityId = obj.cityId ? obj.cityId[obj.cityId.length - 1] : undefined
		obj.hukouProvince = obj.hukouProvince
			? obj.hukouProvince.join(',')
			: undefined
		obj.resideProvince = obj.resideProvince
			? obj.resideProvince.join(',')
			: undefined
		obj.crimeAuthImg =
			fileList?.[0]?.response?.data?.id || fileList?.[0]?.uid || ''

		obj.physicalExaminationImg =
			physicalFileList?.[0]?.response?.data?.id ||
			physicalFileList?.[0]?.uid ||
			''

		if (pageType === PageType.add) {
			request = addDriverRequest(obj)
		} else {
			obj.driverId = routerQuery.id
			request = driverEditRequest(obj)
		}
		request
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
					setBtnLoading(false)
				} else {
					setBtnLoading(false)
				}
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	return (
		<div className={styles.add}>
			<PersonalInformation
				orgList={companyData}
				personalInformationFrom={personalInformationFrom}
				pageType={pageType}
				dirver={routerQuery.dirver}
				dict={dict}
				detailRecord={detailRecord}
			/>
			<ImageInfo
				fileList={fileList}
				setFileList={setFileList}
				physicalFileList={physicalFileList}
				setPhysicalFileList={setPhysicalFileList}
				detailRecord={detailRecord}
				pageType={pageType}
			/>
			<CreditInformation
				dict={dict}
				creditInformationFrom={creditInformationFrom}
				detailRecord={detailRecord}
				pageType={pageType}
			/>
			<HealthInformation
				pageType={pageType}
				detailRecord={detailRecord}
				healthInformationForm={healthInformationForm}
			/>
			<BankCard
				pageType={pageType}
				detailRecord={detailRecord}
				bankCardForm={bankCardForm}
			/>
			<EmergencyContact
				pageType={pageType}
				detailRecord={detailRecord}
				emergencyContactFrom={emergencyContactFrom}
			/>
			<div className={styles.operation}>
				<Button
					type="primary"
					htmlType="submit"
					loading={btnLoading}
					onClick={onSave}>
					保存
				</Button>

				<Button
					style={{marginLeft: '5px;'}}
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				loading={btnLoading}
				onSubmit={onSubmit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(add)
